package top.guxx.mall;

import lombok.Builder;
import org.bouncycastle.util.test.SimpleTest;

import java.util.*;

/**
 * @Author：Guxx
 * @Description：
 * @Date：2025/3/8 17:10
 * @Filename：SimpleTriedTree
 */
public class SimpleTriedTree {
    public static void main(String[] args) {
        TriedTree triedTree = new TriedTree();
        triedTree.insertEle("abc");
        System.out.println(triedTree.existThisTree("abc"));
        System.out.println(triedTree.hasThisStr("abcd"));
        triedTree.insertEle("abcdef");
        System.out.println(triedTree.existThisTree("abc"));
        System.out.println(triedTree.hasThisStr("abcd"));
    }

}

//@Builder
class TriedTree{
    String value;
    int pass = 0;
    int end = 0;
    List<TriedTree> next =  new ArrayList<>();
    Map<String,Integer> nextValues = new HashMap<>();

    public void insertEle(String str){
        //abc
        List<TriedTree> curNext = this.next;
        Map<String,Integer> curMap = this.nextValues;
        String[] split = str.split("");
        for (int i = 0; i < str.length(); i++) {
            if (curMap.containsKey(split[i])){
                Integer index = curMap.get(split[i]);
                TriedTree triedTree = curNext.get(index);
                triedTree.pass++;
                if (i == (str.length()-1)) triedTree.end++;
                curMap = triedTree.nextValues;
                curNext = triedTree.next;
            }else {
                TriedTree triedTree = new TriedTree();
                triedTree.value = split[i];
                triedTree.pass = 1;
                if (i == (str.length()-1)) triedTree.end = 1;
                curNext.add(triedTree);
                curMap.put(split[i],curNext.size()-1);
                curNext = triedTree.next;
                curMap = triedTree.nextValues;
            }
        }
    }
    public boolean existThisTree(String str){
        String[] split = str.split("");
        Map<String, Integer> curMap = this.nextValues;
        List<TriedTree> curNext = this.next;
        int end = 0;
        for (String ele : split) {
            if (!curMap.containsKey(ele)) return false;
            TriedTree triedTree = curNext.get(curMap.get(ele));
            curMap = triedTree.nextValues;
            curNext = triedTree.next;
            end = triedTree.end;
        }
        return end >=1 ? true : false;
    }

    public boolean hasThisStr(String str){
        String[] split = str.split("");
        Map<String, Integer> curMap = this.nextValues;
        List<TriedTree> curNext = this.next;
        for (String ele : split) {
            if (!curMap.containsKey(ele)) return false;
            TriedTree triedTree = curNext.get(curMap.get(ele));
            curMap = triedTree.nextValues;
            curNext = triedTree.next;
            end = triedTree.end;
        }
        return true;
    }
}

class TreeNode{

}